package Jasper.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 要放行的多
 * 1.先判断那些不能放行；
 * 1.1嵌套if(id ==null) 回到登录页面；
 * 2.放行
 * <p>
 * if(不能放行的判断){
 * if(id == null){
 * 回到登录页面
 * return;
 * }
 * }
 * 放行代码;
 */
public class LoginFilter extends DefaultFilter {
    //判断用户是否登录，如果没有登录则跳转到登录页面
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");
        //获取URL
        String uri = request.getRequestURI();
        //打印过去地址
        System.out.println(uri);
        //获取action值
        String action = request.getParameter("action");
        //避免空指针异常
        //action = action == null?"":action;

        //判断是否为首页，登录页面，注册页面
        if (uri.endsWith("index.html") ||
                uri.endsWith("index.html") ||
                uri.endsWith("register.html") ||
                uri.endsWith("CheckServlet") ||
                uri.endsWith(".css") ||
                uri.endsWith(".js") ||
                uri.endsWith(".png") ||
                uri.endsWith(".html") ||
                uri.endsWith("Servlet") ||

                //用于服务服务层未分离的的发放
                "login".equals(action) ||
                "register".equals(action)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }


        //获取session里存储的 id
        Integer id = (Integer) request.getSession().getAttribute("userid");

/*        if(uri.endsWith("update.html")){
            if (id == null){
                response.getWriter().write("<script>location.href='login.html'</script>");
                return;
            }else {
//                放行
                filterChain.doFilter(request,response);
            }
        }*/
        //启动为空
//        System.out.println(id);
        if (id == null) {
            //跳转到登录页面
            response.getWriter().write("<script>location.href='login.html'</script>");
        } else {
            //放行
            filterChain.doFilter(request, response);
        }
    }
}
